#include "logger.h"

#ifdef USE_LOGGER

#include "sqlite3/sqlite3.h"
#include <log4cplus/logger.h>
#include <log4cplus/configurator.h>
#include <log4cplus/helpers/stringhelper.h>

using namespace log4cplus;

#define LOG_LEVEL_TRACE 6
#define LOG_LEVEL_DEBUG 5
#define LOG_LEVEL_INFO  4
#define LOG_LEVEL_WARN  3
#define LOG_LEVEL_ERROR 2
#define LOG_LEVEL_FATAL 1

#define LOGGER_BUFFER_SIZE 512
bool if_load_logger_configurator = false;
char logger_message_buffer[LOGGER_BUFFER_SIZE];
Logger system_logger_instance = Logger::getInstance("NetMonitorLog");

void printLog(int loglevel, const char *format, va_list ap)
{
	char *buffer;

	buffer = sqlite3_vmprintf(format, ap);
	int len = strlen(buffer);
	if ( len>LOGGER_BUFFER_SIZE) len = LOGGER_BUFFER_SIZE-1;
	logger_message_buffer[len] = 0;
	strncpy(logger_message_buffer, buffer, len);
	
	if ( !if_load_logger_configurator ) {
		PropertyConfigurator::doConfigure("NMLogger.properties");
		if_load_logger_configurator = true;
	}

	switch (loglevel)
	{
	case LOG_LEVEL_FATAL:
		LOG4CPLUS_FATAL(system_logger_instance, logger_message_buffer);
		break;
	case LOG_LEVEL_ERROR:
		LOG4CPLUS_ERROR(system_logger_instance, logger_message_buffer);
		break;
	case LOG_LEVEL_WARN:
		LOG4CPLUS_WARN(system_logger_instance, logger_message_buffer);
		break;
	case LOG_LEVEL_INFO:
		LOG4CPLUS_INFO(system_logger_instance, logger_message_buffer);
		break;
	case LOG_LEVEL_DEBUG:
		LOG4CPLUS_DEBUG(system_logger_instance, logger_message_buffer);
		break;
	case LOG_LEVEL_TRACE:
		LOG4CPLUS_TRACE(system_logger_instance, logger_message_buffer);
	}

	sqlite3_free(buffer);
	buffer = NULL;
}
//LOG_LEVEL_TRACE
void logger_trace(const char *format, ...)
{
	va_list ap;
	va_start(ap, format);
	printLog(LOG_LEVEL_TRACE, format, ap);
	va_end(ap);
}
//LOG_LEVEL_DEBUG
void logger_debug(const char *format, ...)
{
	va_list ap;
	va_start(ap, format);
	printLog(LOG_LEVEL_DEBUG, format, ap);
	va_end(ap);
}
//LOG_LEVEL_INFO
void logger_info(const char *format, ...)
{
	va_list ap;
	va_start(ap, format);
	printLog(LOG_LEVEL_INFO, format, ap);
	va_end(ap);
}
//LOG_LEVEL_WARN
void logger_warn(const char *format, ...)
{
	va_list ap;
	va_start(ap, format);
	printLog(LOG_LEVEL_WARN, format, ap);
	va_end(ap);
}
//LOG_LEVEL_ERROR
void logger_error(const char *format, ...)
{
	va_list ap;
	va_start(ap, format);
	printLog(LOG_LEVEL_ERROR, format, ap);
	va_end(ap);
}
//LOG_LEVEL_FATAL
void logger_fatal(const char *format, ...)
{
	va_list ap;
	va_start(ap, format);
	printLog(LOG_LEVEL_FATAL, format, ap);
	va_end(ap);
}

#endif //end #ifdef USE_LOGGER